<template>
  <div class="profile-page">
    <!-- 顶部蓝色渐变区域 -->
    <div class="header">
      <router-link to="/settings" class="header-setting">
        <i class="fas fa-cog"></i>
      </router-link>

      <div class="user-info">
        <img class="avatar" :src="userInfo.avatar || 'https://randomuser.me/api/portraits/men/32.jpg'" alt="用户头像">
        <div class="user-details">
          <div class="username">{{ userInfo.username || '用户名' }}</div>
          <div class="user-id">ID: {{ userInfo.userId || '12345678' }}</div>
          <div class="membership-info">
            <div class="membership">
              <i class="fas fa-crown" style="color: #f6ad55;"></i>
              <span>{{ (userInfo.memberPoints || 0) > 1000 ? '黄金会员' : '普通会员' }}</span>
            </div>
            <div class="qr-code">
              <i class="fas fa-qrcode"></i>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计数据 -->
    <div class="statistics">
      <div class="stat-item">
        <div class="stat-value">{{ userStats.storeFavorites || 0 }}</div>
        <div class="stat-label">商店收藏</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ userStats.productFavorites || 0 }}</div>
        <div class="stat-label">商品收藏</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ userStats.videoFavorites || 0 }}</div>
        <div class="stat-label">视频收藏</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ userStats.points || 0 }}</div>
        <div class="stat-label">积分</div>
      </div>
    </div>

    <!-- 我的订单 -->
    <div class="order-section">
      <div class="order-header">
        <div class="section-title" style="padding: 0;">我的订单</div>
        <router-link to="/orders" class="view-all">
          <span>查看全部</span>
          <i class="fas fa-chevron-right section-arrow"></i>
        </router-link>
      </div>

      <div class="order-types">
        <router-link to="/orders?status=pending_payment" class="order-type">
          <i class="fas fa-credit-card order-type-icon"></i>
          <div class="order-type-name">待付款</div>
          <div class="badge" v-if="orderCounts.pendingPayment > 0">{{ orderCounts.pendingPayment }}</div>
        </router-link>
        <router-link to="/orders?status=pending_shipping" class="order-type">
          <i class="fas fa-box order-type-icon"></i>
          <div class="order-type-name">待发货</div>
          <div class="badge" v-if="orderCounts.pendingShipment > 0">{{ orderCounts.pendingShipment }}</div>
        </router-link>
        <router-link to="/orders?status=pending_receipt" class="order-type">
          <i class="fas fa-truck order-type-icon"></i>
          <div class="order-type-name">待收货</div>
          <div class="badge" v-if="orderCounts.pendingReceipt > 0">{{ orderCounts.pendingReceipt }}</div>
        </router-link>
        <router-link to="/orders?status=completed" class="order-type">
          <i class="fas fa-comment-alt order-type-icon"></i>
          <div class="order-type-name">待评价</div>
          <div class="badge" v-if="orderCounts.pendingReview > 0">{{ orderCounts.pendingReview }}</div>
        </router-link>
        <router-link to="/orders?status=cancelled" class="order-type">
          <i class="fas fa-times-circle order-type-icon"></i>
          <div class="order-type-name">已取消</div>
          <div class="badge" v-if="orderCounts.cancelled > 0">{{ orderCounts.cancelled }}</div>
        </router-link>
      </div>
    </div>

    <!-- 我的服务 -->
    <div class="section-title">我的服务</div>

    <div class="menu-section">
      <router-link to="/address" class="menu-item">
        <div class="menu-icon">
          <i class="fas fa-map-marker-alt location-icon"></i>
        </div>
        <div class="menu-name">收货地址</div>
        <div class="menu-arrow">
          <i class="fas fa-chevron-right"></i>
        </div>
      </router-link>

      <router-link to="/favorites" class="menu-item">
        <div class="menu-icon">
          <i class="fas fa-heart heart-icon" :class="{ 'is-favorited': userStats.storeFavorites > 0 }"></i>
        </div>
        <div class="menu-name">我的收藏</div>
        <div class="menu-arrow">
          <i class="fas fa-chevron-right"></i>
        </div>
      </router-link>
    </div>

    <!-- 客户服务 -->
    <div class="section-title">客户服务</div>

    <div class="menu-section">
      <div class="menu-item" @click="contactCustomerService">
        <div class="menu-icon">
          <i class="fas fa-headset"></i>
        </div>
        <div class="menu-name">在线客服</div>
        <div class="menu-arrow">
          <i class="fas fa-chevron-right"></i>
        </div>
      </div>

      <router-link to="/help" class="menu-item">
        <div class="menu-icon">
          <i class="fas fa-question-circle"></i>
        </div>
        <div class="menu-name">帮助中心</div>
        <div class="menu-arrow">
          <i class="fas fa-chevron-right"></i>
        </div>
      </router-link>
    </div>

    <!-- 底部导航 -->
    <TabBar active-tab="profile" />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { api } from '@/network/api';
import TabBar from '@/components/TabBar.vue';
import { showToast, showDialog } from 'vant';

interface UserInfo {
  avatar: string;
  username: string;
  userId: string;
  memberLevel: number;
  memberPoints: number;
}

interface UserStats {
  storeFavorites: number;
  productFavorites: number;
  videoFavorites: number;
  points: number;
}

interface OrderCounts {
  pendingPayment: number;
  pendingShipment: number;
  pendingReceipt: number;
  pendingReview: number;
  cancelled: number;
}

export default defineComponent({
  name: 'ProfileView',
  components: {
    TabBar
  },
  setup() {
    const userInfo = ref<Partial<UserInfo>>({});

    const userStats = ref<UserStats>({
      storeFavorites: 0,
      productFavorites: 0,
      videoFavorites: 0,
      points: 0
    });

    const orderCounts = ref<OrderCounts>({
      pendingPayment: 0,
      pendingShipment: 0,
      pendingReceipt: 0,
      pendingReview: 0,
      cancelled: 0
    });

    const isLoading = ref(false);

    // 获取用户信息
    const fetchUserProfile = async () => {
      try {
        isLoading.value = true;
        const response: any = await api.getUserProfile();
        if (response && response.code === 100) {
          userInfo.value = response.data;
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      } finally {
        isLoading.value = false;
      }
    };

    // 获取用户统计数据
    const fetchUserStats = async () => {
      try {
        // 获取用户ID
        let userId = null;
        try {
          const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
          userId = userInfo.data?.userId || userInfo.userId;
          if (!userId) {
            console.error('无法获取用户ID');
            return;
          }
        } catch (e) {
          console.error('解析用户信息失败:', e);
          return;
        }

        // 获取基本统计数据
        try {
          const response: any = await api.getUserStats();
          if (response && response && response.code === 100) {
            userStats.value = {
              storeFavorites: response.data.storeFavorites || 0, // 先初始化为0，后面从专门的API获取
              productFavorites: response.data.productFavorites || 0,
              videoFavorites: response.data.videoFavorites || 0,
              points: response.data.points || 0
            };
          }
        } catch (statsError) {
          console.error('获取基本统计数据失败:', statsError);
          // 设置默认值
          userStats.value = {
            storeFavorites: 0,
            productFavorites: 0,
            videoFavorites: 0,
            points: 0
          };
        }
      } catch (error) {
        console.error('获取用户统计数据失败:', error);
      }
    };


    // 获取订单数量
    const fetchOrderCounts = async () => {
      try {
        const response: any = await api.getOrderCounts();
        if (response && response && response.code === 100) {
          orderCounts.value = {
            pendingPayment: response.data.pendingPayment || 0,
            pendingShipment: response.data.pendingShipment || 0,
            pendingReceipt: response.data.pendingReceipt || 0,
            pendingReview: response.data.pendingReview || 0,
            cancelled: response.data.cancelled || 0
          };
        }
      } catch (error) {
        console.error('获取订单数量失败:', error);
      }
    };

    // 联系客服
    const contactCustomerService = () => {
      showDialog({
        title: '联系客服',
        message: '客服热线: 400-123-4567\n工作时间: 周一至周日 9:00-18:00',
        confirmButtonText: '确定'
      });
    };

    // 领取新人礼包
    const claimNewUserGift = async () => {
      try {
        const response = await api.claimNewUserGift();
        if (response && response.data && response.data.code === 100) {
          showToast('礼包领取成功！');
        } else {
          showToast('您已领取过礼包或不符合领取条件');
        }
      } catch (error) {
        console.error('领取礼包失败:', error);
        showToast('领取礼包失败，请稍后再试');
      }
    };

    onMounted(() => {
      // 显示加载状态
      isLoading.value = true;

      // 并行请求数据
      Promise.all([
        fetchUserProfile(),
        fetchUserStats(),
        fetchOrderCounts()
      ]).finally(() => {
        // 请求完成后隐藏加载状态
        isLoading.value = false;
      });
    });

    return {
      userInfo,
      userStats,
      orderCounts,
      isLoading,
      contactCustomerService,
      claimNewUserGift
    };
  }
});
</script>

<style scoped>
.profile-page {
  padding-bottom: 60px;
  /* 为底部导航栏留出空间 */
}

.header {
  /* background: linear-gradient(to right, #3490dc, #6574cd); */
  background: rgba(240, 240, 240, 0.7); /* 浅灰色毛玻璃效果 */
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  color: #333; /* 深色文字 */
  padding: 40px 15px;
  position: relative;
  border-bottom: 1px solid rgba(0,0,0,0.05);
}

.header-setting {
  position: absolute;
  top: 20px;
  right: 15px;
  color: #333; /* 与 header 文本颜色保持一致 */
  font-size: 18px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  border: 2px solid rgba(255, 255, 255, 0.5);
  object-fit: cover;
  margin-right: 15px;
}

.user-details {
  flex: 1;
}

.username {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.user-id {
  font-size: 12px;
  opacity: 0.8;
}

.membership-info {
  display: flex;
  align-items: center;
}

.membership {
  display: inline-block;
  background-color: rgba(0, 0, 0, 0.05); /* 调整背景色以适应浅色背景 */
  border-radius: 15px;
  padding: 3px 10px;
  font-size: 12px;
}

.qr-code {
  background-color: rgba(0, 0, 0, 0.05); /* 调整背景色以适应浅色背景 */
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 10px;
}

.statistics {
  display: flex;
  justify-content: space-around;
  background-color: white;
  padding: 15px 0;
  border-radius: 10px;
  margin: -20px 15px 15px;
  position: relative;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #2d3748;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #718096;
}

.section-title {
  padding: 15px;
  font-weight: 500;
  color: #4a5568;
  font-size: 16px;
}

.order-section {
  background-color: white;
  border-radius: 10px;
  margin: 0 15px 15px;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #e2e8f0;
}

.view-all {
  color: #718096;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.section-arrow {
  margin-left: 5px;
}

.order-types {
  display: flex;
  padding: 12px 0;
  overflow-x: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.order-types::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.order-type {
  flex: 0 0 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.order-type-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 8px;
  font-size: 22px;
  color: #4a5568;
}

.order-type-name {
  font-size: 12px;
  color: #4a5568;
}

.badge {
  position: absolute;
  top: -5px;
  right: 15px;
  background-color: #e53e3e;
  color: white;
  border-radius: 10px;
  padding: 0 5px;
  font-size: 10px;
  min-width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-section {
  background-color: white;
  border-radius: 10px;
  margin: 0 15px 15px;
  overflow: hidden;
}

.menu-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #e2e8f0;
  align-items: center;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  width: 20px;
  height: 20px;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #3490dc;
  font-size: 18px;
}

.location-icon {
  color: #3490dc;
}

.robot-icon {
  color: #3490dc;
}

.heart-icon {
  color: #3490dc;
}

.heart-icon.is-favorited {
  color: #e53e3e;
}

.menu-name {
  flex: 1;
  font-size: 14px;
  color: #4a5568;
}

.menu-arrow {
  color: #a0aec0;
}

.gift-section {
  background-color: white;
  border-radius: 10px;
  margin: 0 15px 15px;
  overflow: hidden;
  padding: 15px;
}

.gift-banner {
  background: linear-gradient(to right, #f6ad55, #ed8936);
  border-radius: 8px;
  padding: 15px;
  color: white;
  display: flex;
  align-items: center;
}

.gift-icon {
  font-size: 30px;
  margin-right: 15px;
}

.gift-info {
  flex: 1;
}

.gift-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.gift-desc {
  font-size: 12px;
  opacity: 0.8;
}

.gift-button {
  background-color: white;
  color: #ed8936;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
  cursor: pointer;
}
</style>